let username; //当前登录的用户名
let uid;

$(function () {
    $.ajax({
        url: 'getUsername',
        success: function (data) {
            console.log(data);
            username =data.username;
            uid=data.uid;
            // $('#username').html("<p>用户："+username+"</p><span class='float-right'>在线</span>");
        },
        async: false //非异步的
    });
    let ws = new WebSocket('ws://localhost:8080/chat')
    //连接建立
    ws.onopen = function () {
        $('#username').html("<p>用户："+username+"</p><span class='float-right'>在线</span>");
    }
    //接收到服务端的数据后触发
    ws.onmessage = function (ev) {
        console.log("接收到了消息");

        //获取服务端传来的字符串
        let dataStr = ev.data;
        console.log(dataStr);

        //见字符串转换为对象
        let res = JSON.parse(dataStr);
        if(res.system){//是系统消息
            let names = res.message;
            //好友列表
            let userList = "";
            //系统广播
            let broadcastList = "";

            //遍历
            for (let name of names){
                if(name !== username){
                    userList += "<li><a onclick='showChat(\""+name+"\")'>"+name+"</a></li>";
                    broadcastList += "<li>"+name+"已上线</li>"
                }
            }

            console.log(userList);
            console.log(broadcastList);

            //页面渲染
            $('#userList').html(userList);
            $('#broadcastList').html(broadcastList);

        }else{
            let msg = "<div class=\"media\" style=\"background-color: lightgreen\">" +
                      "   <div class=\"media-body\">" +
                      "      <h5 class=\"mt-0\">"+res.fromName+"</h5>" +
                      "      <p>"+res.message+"</p>" +
                      "   </div>" +
                      "</div>"
            //追加
            if(res.fromName === toName){
                $('#chat-area').append(msg);
            }


            //存储消息
            let chatData = sessionStorage.getItem(res.fromName);
            if(chatData != null){
                msg = chatData + msg;
            }
            sessionStorage.setItem(res.fromName, msg);


        }

    }
    //连接关闭
    ws.onclose = function () {
        $('#username').html("<p>用户："+username+"</p><span class='float-right' style='color: red'>离线</span>");
    }


    //单击发送事件
    $('#submit').click(function (){
        //获取输入区数据
        let data = $('#control-text').val();
        //清空输入区数据
        $('#control-text').val("");
        //json
        let json = {"toName":toName,"message":data};

        //显示到页面上
        let msg = "<div class=\"media\" style=\"background-color: white\">" +
                  "   <div class=\"media-body\">" +
                  "      <h5 class=\"mt-0\">"+username+"</h5>" +
                  "      <p>"+data+"</p>" +
                  "   </div>" +
                  "</div>"
        //追加
        $('#chat-area').append(msg);

        //存储消息
        let chatData = sessionStorage.getItem(toName);
        if(chatData != null){
            msg = chatData + msg;
        }
        sessionStorage.setItem(toName, msg);

        //发送 将json对象转字符串
        ws.send(JSON.stringify(json));
    })

})

let toName; //要聊天的用户名
let showChat = function (name) {
    //点击时，要清空聊天区数据
    $('#chat-area').html("");
    toName = name;
    $('#chat-body').css('display', 'inline');
    $('#message').html("<span class='align-content-center'>正在与"+name+"聊天</span>");
    //sessionStorage用键值对的形式储存聊天记录
    let chatData = sessionStorage.getItem(toName);
    //查看是否有聊天记录，不为空就显示
    if(chatData != null){
        $('#chat-area').html(chatData);
    }
}

